package com.kevin.utility.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {
	public static void analysisTemplate(String templateName,
			String templateEncoding, Map params, String destFile, String srcpath) {
		try {
			Configuration config = new Configuration();

			File writeFile = new File(destFile);
			if (!writeFile.exists()) {
				writeFile.createNewFile();
			}
			OutputStream fileOut = new FileOutputStream(writeFile);

			config.setDirectoryForTemplateLoading(new File(srcpath));

			config.setObjectWrapper(new DefaultObjectWrapper());
			config.setDefaultEncoding("UTF-8");

			Template template = config.getTemplate(templateName,
					templateEncoding);
			template.setEncoding("UTF-8");

			Writer out = new BufferedWriter(new OutputStreamWriter(fileOut,
					"utf-8"));

			template.process(params, out);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}

	public static String executeTemplate(String templateEncoding, Map params, String templateContent)
			throws TemplateException, IOException {
		if (StringUtils.isBlank(templateEncoding)) {
			templateEncoding = "UTF-8";
		}
		Configuration cfg = new Configuration();
		Template template = new Template(null, new StringReader(templateContent), cfg);

		template.setEncoding(templateEncoding);
		// 执行插值，并输出到指定的输出流中
		StringWriter out = new StringWriter();
		template.process(params, out);
		return out.getBuffer().toString();
	}
	public static void main(String[] args) {
		String templateContent = "${.now?date}";
		try {
			String ret = executeTemplate(null, null, templateContent);
			System.out.println(ret);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}